package com.jeeplus.test.jlnu.changeStuInfo.controller;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jeeplus.test.jlnu.changeStuInfo.domain.entity.ChangeStuInfo;
import com.jeeplus.test.jlnu.changeStuInfo.domain.vo.ChangeStuInfoReq;
import com.jeeplus.test.jlnu.changeStuInfo.service.ChangeStuInfoService;
import com.jeeplus.test.jlnu.student.domain.result.Node;
import com.jeeplus.test.tools.resp.R;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;


@RestController
@RequestMapping("/changeStuInfo")
public class ChangeStuInfoController {

    @Autowired
    private ChangeStuInfoService changeStuInfoService;


    //批量修改信息
    @ApiOperation("批量修改")
    @PostMapping("/updateChangeStu")
    public R updateChangeStu(@RequestBody ChangeStuInfo changeStuInfo) {
        if (changeStuInfo == null || changeStuInfo.getStudentIds() == null || changeStuInfo.getStudentIds().isEmpty()) {
            return R.error("9999", "参数为空");
        }
        changeStuInfoService.updateChangeStu(changeStuInfo.getStudentIds(), changeStuInfo);
        return R.suc();
    }

    // 学籍修改申请
    @ApiOperation("提交学籍修改申请")
    @PostMapping("/applyChange")
    public R applyChange(@RequestBody ChangeStuInfo changeStuInfo) {
        // 参数校验
        if (changeStuInfo.getStudentIds() == null || changeStuInfo.getStudentIds().isEmpty()) {
            return R.error("9999", "学号不能为空");
        }
        return changeStuInfoService.processChangeRequest(changeStuInfo);
    }


    /*审批通过接口*/
    @PostMapping("/approval")
    public R approval(@RequestBody Map<String, Object> params) {

        if (!params.containsKey("officeId")) {
            return R.error("9999", "缺少必要参数: officeId");
        }
        if (!params.containsKey("id") || ((List<?>) params.get("id")).isEmpty()) {
            return R.error("9999", "缺少必要参数: id列表");
        }

        try {
            String officeId = (String) params.get("officeId");
            List<Long> ids = ((List<Integer>) params.get("id")).stream()
                    .map(Long::valueOf)
                    .collect(Collectors.toList());

            // 3. 业务处理
            changeStuInfoService.approval(officeId, ids);
            return R.suc();

        } catch (ClassCastException e) {
            return R.error("9999", "参数类型错误");
        }
    }



        /*审批驳回*/
        @PostMapping("/approveRefuse")
        public R approveRefuse(@RequestBody Map<String, Object> params) {
            try {
                String officeId = params.get("officeId").toString(); // 防止类型不匹配

                List<LinkedHashMap<String, Object>> idMaps =
                        (List<LinkedHashMap<String, Object>>) params.get("id");

                List<ChangeStuInfo> changeStuInfos = new ArrayList<>();
                ObjectMapper mapper = new ObjectMapper();

                for (LinkedHashMap<String, Object> dataMap : idMaps) {
                    ChangeStuInfo info = mapper.convertValue(dataMap, ChangeStuInfo.class);
                    changeStuInfos.add(info);
                }

                int count = changeStuInfoService.approveRefuse(officeId, changeStuInfos);
                if(count > 0){
                    R.suc();
                } else {
                    return R.error();
                }
                return R.suc();
            } catch (Exception e) {
                return R.error("参数处理失败: ", e.getMessage());
            }
        }


    @ApiOperation("学籍表信息树")
    @PostMapping("changeStuTree")
    public String changeDirectoryTree(ChangeStuInfoReq changeStuInfoReq) throws JsonProcessingException {
        Map<String, Map<String, List<String>>> tree = new LinkedHashMap<>();
        // 3. 根据院校ID执行查询
        List<ChangeStuInfo> changeStuInfos = changeStuInfoService.selectValueByOfficeId(changeStuInfoReq);

        for (ChangeStuInfo row : changeStuInfos) {
            // 检查 row 是否为 null，防止对 null 进行方法调用
            if (row == null) {
                continue; // 如果 row 为 null，则跳过这次循环
            }

            // 安全地获取各个字段，防止空指针异常
            String academy = row.getCollegeName();
            String major = row.getMajorName();
            String time = row.getGrade();

            // 如果任何一个字段为 null，则不处理该条记录
            if (academy != null && major != null && time != null) {
                tree.computeIfAbsent(academy, k -> new LinkedHashMap<>())
                        .computeIfAbsent(time, k -> new ArrayList<>())
                        .add(major);
                //tree.computeIfAbsent(major, k -> new ArrayList<>());
                // 保证去重
                Set<String> set = new HashSet<>(tree.get(academy).get(time));
                tree.get(academy).put(time, new ArrayList<>(set));
            }
        }

        // 假设convertToTargetFormat方法可以处理空数据并将数据转换为目标格式
        List<Node> formattedTree = convertToTargetFormat(tree);

        // 返回JSON字符串
        return new ObjectMapper().writeValueAsString(formattedTree);
    }

    private List<Node> convertToTargetFormat(Map<String, Map<String, List<String>>> data) {
        List<Node> result = new ArrayList<>();

        if (data == null || data.isEmpty()) {
            return result;
        }

        for (Map.Entry<String, Map<String, List<String>>> academyEntry : data.entrySet()) {
            String academyName = academyEntry.getKey();
            if (academyName == null || academyEntry.getValue() == null || academyEntry.getValue().isEmpty()) {
                continue;
            }

            Node academyNode = new Node(academyName);

            for (Map.Entry<String, List<String>> majorEntry : academyEntry.getValue().entrySet()) {
                String majorName = majorEntry.getKey();
                if (majorName == null || majorEntry.getValue() == null || majorEntry.getValue().isEmpty()) {
                    continue;
                }

                Node majorNode = new Node(majorName);

                for (String time : majorEntry.getValue()) {
                    if (time == null) {
                        continue;
                    }
                    Node timeNode = new Node(time);
                    majorNode.addChild(timeNode);
                }

                if (!majorNode.getChildren().isEmpty()) {
                    academyNode.addChild(majorNode);
                }
            }

            if (!academyNode.getChildren().isEmpty()) {
                result.add(academyNode);
            }
        }
        return result;
    }


}
